let jwt=require('jsonwebtoken')
let {JWT_SECRET}=require('../config/config.default.js')
let {getUser}=require('../server/user.js')

async function auth(ctx,next){
    let {authorization=''}=ctx.request.header
    let token=authorization.replace('Bearer ','')
    try{
       let user=jwt.verify(token,JWT_SECRET)
       ctx.state.user=user
    }catch(err){
        console.log('token----'+err)
       switch(err.name){
           case 'TokenExpiredError':
               console.error('token已过期')
               ctx.app.emit('error',{
                   code:'50000',
                   message:'token已过期',
                   result:''
               },ctx)
               break;
          case 'JsonWebTokenError':
              console.error('无效的token')
              ctx.app.emit('error',{
                 code:'50000',
                 message:"无效的token",
                 result:''
              },ctx);
              break;
          default:break
       }
       return
    }
    
    await next()
}

async function adminPermission(ctx,next){
       let {isAdmin}=ctx.state.user
       if(!isAdmin){
           ctx.app.emit('error',{
               code:40000,
               message:'您不是管理员，没有操作权限',
               result:''
           },ctx)
           return
       }
       await next()

}

module.exports={
    auth,
    adminPermission
}